package one.bugu.android.demon.wxapi;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;

import com.juefeng.android.framework.LKUtil;
import com.juefeng.android.framework.common.dialog.DialogProcess;
import com.juefeng.android.framework.common.util.DeviceUtil;
import com.juefeng.android.framework.common.util.ToastUtils;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.weixin.view.WXCallbackActivity;

import java.util.HashMap;
import java.util.Map;

import one.bugu.android.demon.MyApplication;
import one.bugu.android.demon.bean.WeixinLoginBean;
import one.bugu.android.demon.common.BaseHttpAsycResponceHandler;
import one.bugu.android.demon.common.MyBaseActivity;
import one.bugu.android.demon.constant.Constant;
import one.bugu.android.demon.constant.HttpConstant;
import one.bugu.android.demon.ui.activity.BoundTelActivity;
import one.bugu.android.demon.ui.activity.TelLoginActivity;
import one.bugu.android.demon.ui.activity.WarnMainActivity;
import one.bugu.android.demon.util.IntentUtils;
import one.bugu.android.demon.util.PreferencesUtil;
import one.bugu.android.demon.util.TimerTaskUtils;

/**
 * Created with IntelliJ IDEA.
 * User: LangK
 * Date: 2017/12/9
 * Time: 14:35
 * Description:
 */
public class WXEntryActivity extends WXCallbackActivity implements IWXAPIEventHandler {
    private static final String TAG = "WXEntryActivity";
    private static final int RETURN_MSG_TYPE_LOGIN = 1; //登录
    private static final int RETURN_MSG_TYPE_SHARE = 2; //分享
    private DialogProcess process;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        process = new DialogProcess(this);

        MyApplication.addActivity(this);

        //这句没有写,是不能执行回调的方法的
        MyApplication.mWxApi.handleIntent(getIntent(), this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
    }

    // 微信发送请求到第三方应用时，会回调到该方法
    @Override
    public void onReq(BaseReq baseReq) {

    }

    // 第三方应用发送到微信的请求处理后的响应结果，会回调到该方法
    //app发送消息给微信，处理返回消息的回调
    @Override
    public void onResp(BaseResp baseResp) {
        int type = baseResp.getType(); //类型：分享还是登录
        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                //用户拒绝授权
                finish();
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                //用户取消
                finish();
                break;
            case BaseResp.ErrCode.ERR_OK:
                //用户同意
                if (type == RETURN_MSG_TYPE_LOGIN) {
                    //用户换取access_token的code，仅在ErrCode为0时有效
                    String code = ((SendAuth.Resp) baseResp).code;
                    getWXLoginResult(code);
                } else if (type == RETURN_MSG_TYPE_SHARE) {
                    finish();
                }
                break;
        }
    }

    /**
     * 与服务器交互,获取登录状态
     */
    private void getWXLoginResult(String code) {
        String deviceToken = PreferencesUtil.getInstance().getString(getApplicationContext(), "deviceToken");
        //deviceToken 为空时,使用设备ID, 并使用UUID_进行标识
        if (TextUtils.isEmpty(deviceToken)) {
            deviceToken = "UUID_" + DeviceUtil.getDeviceId(this);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("code", code);
        map.put("regFrom", "50");
        map.put("ymDeviceId", deviceToken);
        LKUtil.getHttpManager().postBody(HttpConstant.WEIXIN_LOGIN, map, weChatLoginHandler);
        //显示加载圈
        showProcess();
    }

    @SuppressLint("HandlerLeak")
    private BaseHttpAsycResponceHandler weChatLoginHandler =
            new BaseHttpAsycResponceHandler<WeixinLoginBean>() {

                @Override
                public void onSuccess(WeixinLoginBean winInfo) {
                    super.onSuccess(winInfo);
                    dismissProcess();
                    ToastUtils.custom("登录成功");
                    //登录成功后, 存储token, 以后要用到
                    PreferencesUtil.getInstance().putString(WXEntryActivity.this, Constant.TOKEN, winInfo.getToken());
                    //登录成功后, 存储邀请码
                    PreferencesUtil.getInstance().putString(WXEntryActivity.this, Constant.INVITE_CODE, winInfo.getInviteCode());
                    //用户昵称
                    boolean flag = winInfo.getNickname() != null && !TextUtils.isEmpty(winInfo.getNickname());
                    String name = flag ? winInfo.getNickname() : "";
                    //保存昵称
                    PreferencesUtil.getInstance().putString(WXEntryActivity.this, Constant.USER_NAMR, name);
                    PreferencesUtil.getInstance().putInt(WXEntryActivity.this, Constant.USER_ID, winInfo.getRowId());
                    //保存头像
                    PreferencesUtil.getInstance().putString(WXEntryActivity.this, Constant.USER_AVATAR, winInfo.getPhoto());
                    //保存客服昵称
                    PreferencesUtil.getInstance().putString(WXEntryActivity.this, Constant.WECHAT_ACCOUNT, winInfo.getWechatAccount());
                    if (TextUtils.equals(winInfo.getIsBP(), "0")) {
                        //未绑定手机手机号,去绑定手机号
                        IntentUtils.startAty(WXEntryActivity.this, BoundTelActivity.class);
                        finish();
                    } else {
                        //记录为登录状态
                        PreferencesUtil.getInstance().putBoolean(WXEntryActivity.this, Constant.IS_LOGIN, true);
                        //已绑定手机号,直接跳转至农场首页
                        IntentUtils.startAty(WXEntryActivity.this, WarnMainActivity.class);
                        MyApplication.finishAllActivity();
                    }
                }

                @Override
                public void onFailed(int code, String message) {
                    super.onFailed(code, message);
                    dismissProcess();
                    ToastUtils.custom(message);
                    finish();
                }

                @Override
                public void onError() {
                    super.onError();
                    dismissProcess();
                }
            };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyApplication.removeActivity(this);
        TimerTaskUtils.getInstance().endTimerTask();
    }

    /**
     * 隐藏进度框
     */
    private void dismissProcess() {
        if (process != null && process.isShowing()) {
            process.dismiss();
        }
    }

    /**
     * 显示进度框
     */
    private void showProcess() {
        if (process == null) {
            return;
        }
        process.show();
        //开启定时任务, 防止请求其他情况下不隐藏进度
        TimerTaskUtils.getInstance().startSingleTimerTask(10, new TimerTaskUtils.OnTimerTaskEvent() {
            @Override
            public void onTickEvent(long millisUntilFinished) {

            }

            @Override
            public void onFinishEvent() {
                dismissProcess();
            }
        });
    }


}
